<template>
	<view class="weather-container list-p">
		<view class="text-color-5">
			<i class="iconfont icon-mojitianqi-1 fz-42 we-icon"></i> 天气 ｜ <i class="iconfont icon-dingwei"></i>
			{{address}}
		</view>
		<view v-if="weatherData.length>0" class="flex-start list-py gap-10">
			<image class="main-image" :src=" weatherData[0].icon" mode=""></image>
			<view>
				<view class="main-date fz-32">
					{{weatherData[0].dayName}} {{ weatherData[0].date }}
				</view>
				<view class="main-temp fz-32">
					{{ weatherData[0].highTemp }}° / {{ weatherData[0].lowTemp }}°
				</view>
			</view>


		</view>
		<view v-if="weatherData.length>0" class="flex-between">
			<view v-for="(item,index) in weatherData.slice(1)" :key="index" class="flex-start gap-10">
				<view>
					<image class="list-image" :src="item.icon" mode=""></image>
				</view>
				<view>
					<view class="fz-24 ">
						{{item.dayName}} {{ item.date }}
					</view>
					<view class="fz-24">
						{{ item.highTemp }}° / {{ item.lowTemp }}°
					</view>

				</view>
			</view>
		</view>
		<!-- 天气信息区域 -->
		<!-- 	<div class="weather-grid">
			<div v-for="(item, index) in weatherData" :key="index"
				:class="['weather-day', index === 0 ? 'active' : '']">
				<div class="day-name">{{ item.dayName }}</div>
				<div class="date">{{ item.date }}</div>
				<div class="weather-desc">{{ item.weatherDesc }}</div>
				<div class="weather-icon">
					<img :src="item.icon" alt="天气图标" />
				</div>
				<div class="temp-range">
					<span class="high-temp">{{ item.highTemp }}°</span>
					<span class="temp-separator">/</span>
					<span class="low-temp">{{ item.lowTemp }}°</span>
				</div>
			</div>
		</div> -->

		<!-- 温度折线图 -->
		<!-- 	<div class="temperature-chart">
			<canvas ref="tempCanvas" canvas-id="tempCanvas" class="temp-canvas" type='2d'></canvas>
		</div> -->
	</view>
</template>

<script setup lang="ts">
	import { computed, toRefs, ref, onUnmounted, onMounted, watch } from "vue"
	import dayjs from "dayjs";
	import 'dayjs/locale/zh-cn';

	// 静态导入图片资源（使用 static 资源路径）
	import wind from "@/assets/weather/wind.png";
	import cloudy from "@/assets/weather/cloudy.png";
	import snow from "@/assets/weather/snow.png";
	import fog from "@/assets/weather/fog.png";
	import clearDay from "@/assets/weather/clearDay.png";
	import sleet from "@/assets/weather/sleet.png";
	import rain from "@/assets/weather/rain.png";
	import cloudyDay from "@/assets/weather/cloudyDay.png";


	// 图标映射
	const weatherIcons : Record<string, string> = {
		wind,
		cloudy,
		snow,
		fog,
		clearDay,
		sleet,
		rain,
		cloudyDay,
	};

	const iconWeatherMap = {
		'wind': ['有风', '平静', '微风', '和风', '清风', '强风/劲风', '疾风', '大风', '烈风', '风暴', '狂爆风', '飓风', '热带风暴', '龙卷风'],
		'cloudy': ['少云', '晴间多云', '多云'],
		'snow': ['雪', '阵雪', '小雪', '中雪', '大雪', '暴雪', '小雪-中雪', '中雪-大雪', '大雪-暴雪', '冷'],
		'fog': ['浮尘', '扬沙', '沙尘暴', '强沙尘暴', '雾', '浓雾', '强浓雾', '轻雾', '大雾', '特强浓雾'],
		'clearDay': ['晴', '热'],
		'sleet': ['雨雪天气', '雨夹雪', '阵雨夹雪'],
		'rain': ['阵雨', '雷阵雨', '雷阵雨并伴有冰雹', '小雨', '中雨', '大雨', '暴雨', '大暴雨', '特大暴雨', '强阵雨', '强雷阵雨', '极端降雨', '毛毛雨/细雨', '雨', '小雨-中雨', '中雨-大雨', '大雨-暴雨', '暴雨-大暴雨', '大暴雨-特大暴雨', '冻雨'],
		'cloudyDay': ['阴', '霾', '中度霾', '重度霾', '严重霾', '未知']
	}
	dayjs.locale('zh-cn');

	const props = defineProps({
		weatherInfo: {
			type: Object,
			default: () => ({}),
		},
	});
	const { weatherInfo } = toRefs(props);




	const today = dayjs().startOf('day'); // 获取今天的 00:00:00
	const tomorrow = today.add(1, 'day'); // 获取明天的 00:00:00

	const dayName = (date) => {
		const day = dayjs(date).startOf('day');
		if (day.isSame(today, 'day')) {
			return '今天';
		} else if (day.isSame(tomorrow, 'day')) {
			return '明天';
		} else {
			return day.format('dddd').replace('星期', '周');; // 显示星期几，例如：星期一
		}
	};

	function getIcon(weather) {
		console.log(weather, "--==")
		// // 这个是icon的默认值
		let url = ""
		for (const key in iconWeatherMap) {
			if (iconWeatherMap[key].includes(weather)) {
				return weatherIcons[key]
			}
		}

		return ""

	}
	// 获取天气数据
	const weatherData = computed(() => {

		if (!weatherInfo.value?.forecasts) {
			return []
		}
		return weatherInfo.value?.forecasts[0]?.casts?.map((item) => {
			return {
				dayName: dayName(item.date),
				date: dayjs(item.date).format('MM/DD'),
				weatherDesc: item.dayweather,
				icon: getIcon(item.dayweather),
				highTemp: item.daytemp,
				lowTemp: item.nighttemp,
			};
		})
	})
	const address = computed(() => {

		if (!weatherInfo.value?.forecasts) {
			return []
		}
		return weatherInfo.value?.forecasts[0]?.city
	})

	const tempCanvas = ref(null);

	// 绘制温度折线图
	const drawTemperatureChart = () => {
		console.log("执行4")
		const canvas = tempCanvas.value;
		if (!canvas) return;

		const ctx = uni.createCanvasContext('tempCanvas');
		if (!ctx) return;
		console.log("执行5", canvas)

		const container = canvas.parentElement;
		if (!container) return;
		console.log("执行6")
		// 获取设备像素比
		const dpr = window.devicePixelRatio || 1;

		// 设置canvas的实际大小
		const rect = container.getBoundingClientRect();
		canvas.width = rect.width * dpr;
		canvas.height = rect.height * dpr;

		// 设置canvas的显示大小
		canvas.style.width = `${rect.width}px`;
		canvas.style.height = `${rect.height}px`;

		// 缩放绘图上下文以匹配设备像素比
		ctx.scale(dpr, dpr);

		const width = rect.width;
		const height = rect.height;

		// 清空画布
		ctx.clearRect(0, 0, width, height);

		// 设置线条样式
		ctx.lineWidth = 1;
		ctx.lineCap = 'round';
		ctx.lineJoin = 'round';

		// 计算每个点的位置
		const pointCount = weatherData.value.length;
		const columnWidth = width / pointCount;

		// 获取温度范围
		const temps = weatherData.value.flatMap((item) => [item.highTemp, item.lowTemp]);
		const maxTemp = Math.max(...temps);
		const minTemp = Math.min(...temps);
		const tempRange = maxTemp - minTemp;

		// 计算温度到y坐标的转换函数
		const tempToY = (temp : number) => {
			const padding = height * 0.2;
			return padding + ((maxTemp - temp) / tempRange) * (height - padding * 2);
		};

		// 计算x坐标的函数（每列的中心点）
		const getX = (index : number) => columnWidth * (index + 0.5);

		// 启用抗锯齿
		ctx.imageSmoothingEnabled = true;
		ctx.imageSmoothingQuality = 'high';

		// 绘制高温折线
		ctx.beginPath();
		ctx.strokeStyle = '#ff6b6b';
		weatherData.value.forEach((item, index) => {
			const x = getX(index);
			const y = tempToY(item.highTemp);
			if (index === 0) {
				ctx.moveTo(x, y);
			} else {
				ctx.lineTo(x, y);
			}
		});
		ctx.stroke();

		// 绘制高温点
		weatherData.value.forEach((item, index) => {
			const x = getX(index);
			const y = tempToY(item.highTemp);

			// 绘制外圈
			ctx.beginPath();
			ctx.arc(x, y, 3, 0, Math.PI * 2);
			ctx.fillStyle = '#ff6b6b';
			ctx.fill();

			// 绘制内圈
			ctx.beginPath();
			ctx.arc(x, y, 2, 0, Math.PI * 2);
			ctx.fillStyle = '#ffffff';
			ctx.fill();
		});

		// 绘制低温折线
		ctx.beginPath();
		ctx.strokeStyle = '#4dabf7';
		weatherData.value.forEach((item, index) => {
			const x = getX(index);
			const y = tempToY(item.lowTemp);
			if (index === 0) {
				ctx.moveTo(x, y);
			} else {
				ctx.lineTo(x, y);
			}
		});
		ctx.stroke();

		// 绘制低温点
		weatherData.value.forEach((item, index) => {
			const x = getX(index);
			const y = tempToY(item.lowTemp);

			// 绘制外圈
			ctx.beginPath();
			ctx.arc(x, y, 3, 0, Math.PI * 2);
			ctx.fillStyle = '#4dabf7';
			ctx.fill();

			// 绘制内圈
			ctx.beginPath();
			ctx.arc(x, y, 2, 0, Math.PI * 2);
			ctx.fillStyle = '#ffffff';
			ctx.fill();

		});
		console.log("执行完毕")
	};

	// 调整canvas大小
	const resizeCanvas = () => {
		if (!tempCanvas.value) return;
		console.log("执行3")
		drawTemperatureChart();
	};


	// 监听 weatherData 变化
	watch(
		weatherData,
		(newVal, oldVal) => {
			console.log("执行2")
			// resizeCanvas()
		},
		{ deep: true } // 如果是数组或对象，deep 监听确保检测到内部变化
	);
	onMounted(() => {
		console.log("执行1")
	})
</script>

<style scoped lang="scss">
	.weather-container {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		color: #fff;
		border-radius: 30rpx;
		overflow: hidden;
		position: relative;
		background: linear-gradient(45deg, #7b90c5, #66b7ff);
	}
	
	.list-p {
		padding: 0 32rpx;
	}

	.we-icon {
		position: relative;
		top: 4rpx;
	}

	.main-image {
		width: 100rpx;
		height: 100rpx;
	}

	.main-date {}

	.main-temp {}

	.list-image {
		width: 50rpx;
		height: 50rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.weather-grid {
		display: grid;
		grid-template-columns: repeat(4, 1fr);
		width: 100%;
		height: 70%;
	}

	.weather-day {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		text-align: center;
		padding: 5rpx;
		gap: 8rpx;
		position: relative;

		&.active::after {
			content: '';
			position: absolute;
			top: 0;
			left: 50%;
			transform: translateX(-50%);
			width: 80%;
			height: 142.86%; // 扩展高度以覆盖温度显示区域
			background-color: #0c2044;
			box-sizing: border-box;
			border: 1rpx solid #4dabf7;
			border-radius: 10rpx !important;
			z-index: 0;
			pointer-events: none;
		}

		// 确保内容在背景之上
		>* {
			position: relative;
			z-index: 1;
		}

		.day-name {
			font-size: 14rpx;
			font-weight: bold;
		}

		.date {
			font-size: 12rpx;
			color: #ccc;
		}

		.weather-desc {
			font-size: 12rpx;
		}

		.weather-icon {
			width: 36rpx;
			height: 36rpx;
			background-color: rgba(255, 255, 255, 0.1);
			border-radius: 4rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			img {
				width: 80%;
				height: 80%;
			}
		}

		.temp-range {
			font-size: 14rpx;
			font-weight: bold;
			display: flex;
			align-items: center;
			gap: 4rpx;

			.high-temp {
				color: #ff6b6b;
			}

			.temp-separator {
				color: #ccc;
				font-size: 14rpx;
			}

			.low-temp {
				color: #4dabf7;
			}
		}
	}

	.temperature-chart {
		position: relative;
		height: 30%;
		width: 100%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		.max-temp {
			position: absolute;
			top: 5rpx;
			color: #ff6b6b;
			font-size: 14rpx;
			font-weight: bold;
		}

		.min-temp {
			position: absolute;
			bottom: 5rpx;
			color: #4dabf7;
			font-size: 14rpx;
			font-weight: bold;
		}
	}

	.temp-canvas {
		position: absolute;
		top: 0;
		left: 50%;
		transform: translateX(-50%);
		height: 100%;
		z-index: 1;
	}

	// 移除不需要的样式
	.temp-values,
	.high-values,
	.low-values {
		display: none;
	}
</style>